package com.tmz.dao;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.tmz.domain.Jornada;
import com.tmz.domain.Partido;
import com.tmz.domain.User;
import com.tmz.utils.QuinielaUtil;

public class JornadasDAOImpl implements JornadasDAO {

	@SessionTarget
	Session session;
	@TransactionTarget
	Transaction transaction;
	
	@SuppressWarnings("unchecked")
	public Jornada getJornadaById(Long id) {
		Jornada quiniela = null;
		try
		{
			System.out.println(id);
			Query query = session.createQuery("from Jornada WHERE jornada_id = ?");
			query.setLong(0, id);
			List<Jornada> courses = query.list();
			if(courses!=null)
				quiniela = courses.get(0);
			else
				System.out.println("courses = null");
		} catch (Exception e) {
			e.printStackTrace();
		} 	
		return quiniela;
	}

	@SuppressWarnings("unchecked")	
	public List<Jornada> listJornadas() {
		List<Jornada> courses = null;
		try {
			Query query = session.createQuery("from Jornada");
			courses = query.list();
			System.out.println(courses.size());
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return courses;
	}
	
	@SuppressWarnings("unchecked")
	public List<Jornada> listJornadasActivas() {
		List<Jornada> courses = null;
		try {
			System.out.println(1);
			Query query = session.createQuery("from Jornada WHERE jornada_fecha >= ?");
			query.setDate(0, QuinielaUtil.getDateActual());
			courses = query.list();			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return courses;
	}	 
	
	@SuppressWarnings("unchecked")	
	public List<Jornada> listJornadasHistorico() {
		List<Jornada> courses = null;
		try {
			Query query = session.createQuery("from Jornada WHERE jornada_fecha <= ?");
			query.setDate(0, QuinielaUtil.getDateActual());
			courses = query.list();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return courses;
	}
	
	@SuppressWarnings("unchecked")
	public void saveJornada(Jornada j){
		try {
			List<Partido> partidos = (List<Partido>) j.getPartidos();
			for (Iterator iterator = partidos.iterator(); iterator.hasNext();) {
				Partido partido = (Partido) iterator.next();
				partido.setJornada(j);
				session.save(partido);
			}
			session.save(j);
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		} 
	}

}
